#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""pytest消息钩子。

使用pytest消息钩子获取异常信息记录并发送。

Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import os

import pytest

from wingman import db_enter
from wingman import send
from wingman import logger
from wingman.common.error import ErrorCode
from config import rules_filter


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """pytest消息钩子。
    使用pytest消息钩子获取异常信息记录并发送。
    """

    # 获取测试结果
    outcome = yield
    rep = outcome.get_result()

    # 如果测试失败，可以访问这些变量
    if rep.when == "call" and rep.failed:

        # 获取测试方法名
        # test_method_name = item.originalname
        test_method_name = item.name.split("[")[0]
        # 获取测试文件名
        test_file_name = os.path.splitext(item.location[0].split("/")[-1])[0]

        # 检查是否存在 test_method_name + "_filtered_keys"
        variable_name = test_method_name + "_filtered_keys"
        if hasattr(rules_filter, variable_name):
            function_name = test_method_name
        else:
            function_name = test_file_name

        if hasattr(rep, "longrepr"):
            error_message = str(rep.longrepr)
            # 如果有断言值，提取 E 开头的第一行；否则提取最后一行报错信息中第二个 : 后面的内容
            if "AssertionError" in error_message:
                # 提取 E 开头的第一行
                e_lines = [line for line in error_message.split("\n") if line.strip().startswith("E")]
                if e_lines:
                    assertion_value = e_lines[0].strip()  # 取第一行
                else:
                    assertion_value = "无断言错误"
            else:
                # 提取最后一行报错信息中第二个 : 后面的内容
                last_line = error_message.strip().split("\n")[-1]  # 取最后一行
                assertion_value = last_line.split(":", 2)[-1].strip()  # 取第二个 : 后面的内容

        # 从parametrize参数中获取site_params
        site_params = item.callspec.params.get('site_params')
        if site_params:
            domain, ip, port, http, epic, feature, story, tag, description, severity, testcase, issue, link, uri = site_params
            result = {"title": f"{test_file_name}", "domain": f"{domain}", "ip": f"{ip}", "port": f"{port}", "http": f"{http}", "assertion": f"{assertion_value}", "customize_env": f"{epic}", "feature": f"{feature}", "story": f"{story}", "tag": f"{tag}", "description": f"{description}", "severity": f"{severity}", "testcase": f"{testcase}", "issue": f"{issue}", "link": f"{link}"}

            logger.debug(ErrorCode.SUCCESS.value, f"{result} ", __name__)

            send(result, function_name)
            db_enter(result, function_name, "local")
            # db_enter(result, "get_inspection_assertion_exception", "local")

    # logger.info(ErrorCode.SUCCESS.value, f"{outcome}", "configtest")
